<?php

namespace App\Containers\AppSection\Questionnaire\Tasks;

use App\Containers\AppSection\Questionnaire\Data\Criterias\RequiredFormsCriteria;
use App\Containers\AppSection\Questionnaire\Data\Repositories\FormRepository;
use App\Containers\AppSection\Questionnaire\Data\Repositories\QuestionnaireRepository;
use App\Containers\AppSection\Questionnaire\Data\Repositories\ResponseRepository;
use App\Containers\AppSection\Questionnaire\Data\Repositories\ValueRepository;
use App\Containers\AppSection\Questionnaire\Models\Questionnaire;
use App\Ship\Exceptions\CreateResourceFailedException;
use App\Ship\Parents\Tasks\Task;
use Exception;

class CreateDefaultQuestionnairesTask extends Task
{

    protected QuestionnaireRepository $repository;
    protected FormRepository $formRepository;
    protected ResponseRepository $responseRepository;
    protected ValueRepository $valueRepository;

    public function __construct(
        QuestionnaireRepository $repository,
        FormRepository          $formRepository,
        ResponseRepository      $responseRepository,
        ValueRepository         $valueRepository
    )
    {
        $this->valueRepository = $valueRepository;
        $this->responseRepository = $responseRepository;
        $this->formRepository = $formRepository;
        $this->repository = $repository;

    }

    public function run(string $legalFormType, int $legalFormId): Questionnaire
    {
        try {
            //Создание Анкеты
            $questionnaire = $this->repository->create([
                'legal_form_type' => $legalFormType,
                'legal_form_id' => $legalFormId,
            ]);
            $forms = $this->formRepository
                ->with(['fields'])
                ->pushCriteria(new RequiredFormsCriteria($legalFormType))
                ->get();

            if (empty($forms))
                throw new Exception('Пустая Анкета!', 500);

            foreach ($forms as $form) {
                $response = $this->responseRepository->create([
                    'questionnaire_id' => $questionnaire->id,
                    'form_id' => $form->id
                ]);
                foreach ($form->fields as $field) {
                    $this->valueRepository->create([
                        'response_id' => $response->id,
                        'field_id' => $field->id,
                        'value' => $field->default
                    ]);
                }
            }
        } catch (Exception $exception) {
            throw new CreateResourceFailedException();
        }

        return $questionnaire;
    }
}
